﻿using System.Diagnostics;
using Language.Scc;
using Language.Stub;
using Language.Utility;
using Microsoft.VisualStudio.Text;

namespace Language.Parser
{
    internal class Scc
    {
        #region Private Data

        private ITextBuffer _buffer;
        private Connection _connection;
        private Database _database;

        #endregion Private Data

        #region Public Properties

        public FilePath FilePath { get; private set; } = new FilePath();

        public ITextSnapshot Snapshot => _buffer.CurrentSnapshot;

        #endregion Public Properties

        #region C-Tor

        internal Scc( ITextBuffer buffer, Connection connection, Database database )
        {
            _buffer = buffer;
            _connection = connection;
            _database = database;
            FilePath.Absolute = _buffer.ExtractFilename();

            _buffer.PostChanged += _buffer_PostChanged;
            _database.Updated += _database_Updated;

            Parse();
        }

        private void _database_Updated( object sender, Database.SnapshotUpdatedArgs args )
        {
            if ( args.File == FilePath.Relative )
            {
                ParseComplete?.Invoke( new SnapshotSpan( args.Snapshot, Span.FromBounds( 0, args.Snapshot.Length ) ), args.Snapshot );
            }
        }

        #endregion C-Tor

        #region Private Methods

        private async void Parse()
        {
            await _connection.Parse( FilePath.Absolute, _buffer.CurrentSnapshot );
        }

        #endregion Private Methods

        #region Event Handlers

        private void _buffer_PostChanged( object sender, System.EventArgs e )
        {
            Parse();
        }

        #endregion Event Handlers

        #region Events

        public delegate void ParseCompleteHandler( SnapshotSpan snapshotSpan, ITextSnapshot snapshot );
        public event ParseCompleteHandler ParseComplete;

        #endregion Events
    }
}
